import Vapor

struct ReferenceVideoController: RouteCollection {

  func boot(routes: RoutesBuilder) throws {
    let routes = routes.grouped("api", "referencevideo")
//    routes.get(use: getAllHandler)
    routes.post(use: createHandler)
//    routes.get(":id", use: getHandler)
    routes.put(use: updateHandler)
    routes.delete(":id", use: deleteHandler)
//    routes.get("search", use: searchHandler)
//    routes.get("first", use: getFirstHandler)
//    routes.get("sorted", use: sortedHandler)
//    routes.get(":simplebuildingID", "project", use: getProjectHandler)
  }

//    func getAllHandler(_ req: Request) throws -> EventLoopFuture<[SimpleBuilding]> {
//        SimpleBuilding.query(on: req.db).all()
//    }
    
    func createHandler(_ req: Request) throws -> EventLoopFuture<ReferenceVideo> {
      let data = try req.content.decode(ReferenceVideoData.self)
        let video = ReferenceVideo(id: data.id, fileOcId: data.fileOcId , referenceID: data.referenceID ?? UUID())
      return video.save(on: req.db).map { video }
    }

//    func getHandler(_ req: Request) throws -> EventLoopFuture<SimpleBuilding> {
//        SimpleBuilding.find(req.parameters.get("simplebuildingID"), on: req.db)
//      .unwrap(or: Abort(.notFound))
//    }

    func updateHandler(_ req: Request) throws -> EventLoopFuture<ReferenceVideo> {
      let updateData = try req.content.decode(ReferenceVideoData.self)
        return ReferenceVideo.find(updateData.id, on: req.db)
        .unwrap(or: Abort(.notFound)).flatMap { video in
            video.id = updateData.id
            video.fileOcId = updateData.fileOcId
            video.$reference.id = updateData.referenceID ?? UUID()
          return video.save(on: req.db).map {
            video
          }
      }
    }

    func deleteHandler(_ req: Request)
      throws -> EventLoopFuture<HTTPStatus> {
        ReferenceVideo.find(req.parameters.get("id"), on: req.db)
        .unwrap(or: Abort(.notFound))
        .flatMap { video in
            video.delete(on: req.db)
            .transform(to: .noContent)
      }
    }

//    func searchHandler(_ req: Request) throws -> EventLoopFuture<[SimpleBuilding]> {
//      guard let searchTerm = req
//        .query[String.self, at: "term"] else {
//        throw Abort(.badRequest)
//      }
//        return SimpleBuilding.query(on: req.db).group(.or) { or in
//            or.filter(\.$name == searchTerm)
//            or.filter(\.$name == searchTerm)
//
//
//        }.all()
//    }

}

struct ReferenceVideoData: Content {
    var id: UUID?
    var fileOcId: String
    var referenceID: UUID?
    
    
}
